﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Controls_RepliesMVPControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.UserAgent == "GeoTwitter")
            Cache["UserAgentGeo"] = DateTime.Now;
        else
        {
            if (Cache["UserAgentGeo"] != null)
                Label1.Text = "Last update: " + Cache["UserAgentGeo"].ToString();
        }

        if (Cache["RepliesSuccess"] != null)
            Label1.Text += " Last Success: " + Cache["RepliesSuccess"].ToString();

        MVPLoader loader = new MVPLoader();
        loader.Run(HttpContext.Current);

        DataClassesDataContext data = new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["GeoTwitterDataConnectionString"].ConnectionString);
        
        DataTable dataTable = new DataTable("status");
        dataTable.Columns.Add("Name");
        dataTable.Columns.Add("Count");

        var g = data.Replies.GroupBy(a => a.UserName);
        foreach (var pc in g)
        {
            //Console.WriteLine(pc.Key + " - " + pc.Count().ToString());
            DataRow row = dataTable.NewRow();
            row["name"] = pc.Key;
            row["count"] = pc.Count().ToString();
            
            dataTable.Rows.Add(row);
        }

        //var rows = (from o in data.Replies select o.UserName);
        //var rowCount = from t in rows select rows.GroupBy(item => item);

        DataView v = dataTable.DefaultView;
        v.Sort = "Count DESC";
        dataTable = v.ToTable();


        GridView1.DataSource = dataTable;
        GridView1.DataBind();
    }
}
